/*
 *	Copyright (C) 2008 CRIMERE
 *	Copyright (C) 2008 Jean-Marc Mercier
 *	
 *	This file is part of OTS (optimally transported schemes), an open-source library
 *	dedicated to scientific computing. http://code.google.com/p/optimally-transported-schemes/
 *
 *	CRIMERE makes no representations about the suitability of this
 *	software for any purpose. It is provided "as is" without express or
 *	implied warranty.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/*! \file observable.hpp
    \brief observer/observable pattern
*/

#ifndef _os_observable_
#define _os_observable_

#include <src/miscellaneous/OS_basic.h>
#include <list>

namespace OS {

    class Observer;

    //! Object that notifies its changes to a set of observables
    /*! \ingroup patterns */
	class Observable {
      public:
        friend class Observer;
        // constructors, assignment, destructor
        Observable() {}
        Observable(const Observable&);
        Observable& operator=(const Observable&);
        virtual ~Observable() {}
        /*! This method should be called at the end of non-const methods
            or when the programmer desires to notify any changes.
        */
        void notifyObservers();
      private:
        void registerObserver(Observer*);
        void unregisterObserver(Observer*);
        std::list<Observer*> observers_;
        typedef std::list<Observer*>::iterator iterator;
    };


    //! Object that gets notified when a given observable changes
    /*! \ingroup patterns */
    class Observer {
      public:
        // constructors, assignment, destructor
        Observer() {}
        Observer(const Observer&);
        Observer& operator=(const Observer&);
        virtual ~Observer();
        // observer interface
        void registerWith(const smart_ptr<Observable>&);
        void unregisterWith(const smart_ptr<Observable>&);
        /*! This method must be implemented in derived classes. An
            instance of %Observer does not call this method directly:
            instead, it will be called by the observables the instance
            registered with when they need to notify any changes.
        */
        virtual void update() = 0;
      private:
        std::list<smart_ptr<Observable> > observables_;
        typedef std::list<smart_ptr<Observable> >::iterator iterator;
    };

	template <class T> 
	class Observable_helper : public T, public Observable
	{
	public :
		~Observable_helper() {};
		Observable_helper() {};
		Observable_helper(const T & from) : T(from)
		{
		};
		Observable_helper& operator=(const Observable_helper& from) {
			T::operator = (from);
			Observable::operator = (from);
			return *this;
		};
	};
    // inline definitions

    inline Observable::Observable(const Observable&) {
        // the observer list is not copied; no observer asked to
        // register with this object
    }

    /*! \warning notification is sent before the copy constructor has
                 a chance of actually change the data
                 members. Therefore, observers whose update() method
                 tries to use their observables will not see the
                 updated values. It is suggested that the update()
                 method just raise a flag in order to trigger
                 a later recalculation. 
				 jmm : or using the template workaround  Observable_helper<T> (see below)
    */
    inline Observable& Observable::operator=(const Observable& o) {
        // as above, the observer list is not copied. Moreover,
        // observers of this object must be notified of the change
        if (&o != this)
            notifyObservers();
        return *this;
    }

    inline void Observable::registerObserver(Observer* o) {
        observers_.push_front(o);
    }

    inline void Observable::unregisterObserver(Observer* o) {
        iterator i = std::find(observers_.begin(),observers_.end(),o);
        if (i != observers_.end())
            observers_.erase(i);
    }

    inline void Observable::notifyObservers() {
        bool successful = true;
        for (iterator i=observers_.begin(); i!=observers_.end(); ++i) {
//            try {
                (*i)->update();
//            } 
/*			catch (...) {
                // quite a dilemma. If we don't catch the exception,
                // other observers will not receive the notification
                // and might be left in an incorrect state. If we do
                // catch it and continue the loop (as we do here) we
                // lose the exception. The least evil might be to try
                // and notify all observers, while raising an
                // exception if something bad happened.
		        OS_DYNAMIC_CHECK(false);
            }*/
        }
    }


    inline Observer::Observer(const Observer& o)
    : observables_(o.observables_) {
        for (iterator i=observables_.begin(); i!=observables_.end(); ++i)
            (*i)->registerObserver(this);
    }

    inline Observer& Observer::operator=(const Observer& o) {
        iterator i;
        for (i=observables_.begin(); i!=observables_.end(); ++i)
            (*i)->unregisterObserver(this);
        observables_ = o.observables_;
        for (i=observables_.begin(); i!=observables_.end(); ++i)
            (*i)->registerObserver(this);
        return *this;
    }

    inline Observer::~Observer() {
        for (iterator i=observables_.begin(); i!=observables_.end(); ++i)
            (*i)->unregisterObserver(this);
    }

    inline void Observer::registerWith(
                                     const smart_ptr<Observable>& h) {
        if (h) {
            observables_.push_front(h);
            h->registerObserver(this);
        }
    }

    inline void Observer::unregisterWith(
                                    const smart_ptr<Observable>& h) {
        if (h) {
            for (iterator i=observables_.begin();
                 i!=observables_.end();
                 ++i) {
                if (*i == h) {
                    (*i)->unregisterObserver(this);
                    observables_.erase(i);
                    return;
                }
            }
        }
    }

}


#endif
